// API 基础配置
const API_BASE_URL = '/api/v1';

// API 请求路径
const API_ROUTES = {
  register: '/register',
  login: '/login',
  refreshToken: '/token/refresh',
  getUserScore: '/score/current',
  ask: '/ask/start',
  rechargePoints: '/score/recharge',
  createOrder: '/order/create',
  createPayUrl: '/order/create_pay_url',
  signIn: '/score/sign',
  checkSignIn: '/score/sign/check',
  updateBirthday: '/user/update/birthday',
  updateGender: '/user/update/gender',
  getUserDetail: '/user/detail',
  // 其他 API 路径可以根据需要添加
};

// 获取认证头信息
const getAuthHeader = () => {
  const token = localStorage.getItem('token');
  return token ? { 'Authorization': `Bearer ${token}` } : {};
};

// 获取刷新令牌
const getRefreshToken = () => {
  return localStorage.getItem('refreshToken');
};

// 保存令牌信息
const saveTokens = (token, refreshToken) => {
  localStorage.setItem('token', token);
  if (refreshToken) {
    localStorage.setItem('refreshToken', refreshToken);
  }
};

// 刷新令牌
const refreshAuthToken = async () => {
  const refreshToken = getRefreshToken();
  if (!refreshToken) {
    console.error('没有刷新令牌');
    return null;
  }
  
  try {
    const response = await fetch(`${API_BASE_URL}${API_ROUTES.refreshToken}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ refresh_token: refreshToken }),
    });
    
    if (!response.ok) {
      console.error('刷新令牌失败:', response.status);
      return null;
    }
    
    const data = await response.json();
    if (data.success && data.data?.token) {
      // 保存新令牌
      saveTokens(data.data.token, data.data.refresh_token);
      return data.data.token;
    }
    
    return null;
  } catch (error) {
    console.error('刷新令牌错误:', error);
    return null;
  }
};

// 通用请求方法
const fetchAPI = async (endpoint, options = {}, requiresAuth = false) => {
  const url = `${API_BASE_URL}${endpoint}`;
  console.log(`🌐 API请求: ${options.method || 'GET'} ${url}`, options.body ? JSON.parse(options.body) : '');
  
  // 默认请求头
  const headers = {
    'Content-Type': 'application/json',
    ...options.headers,
  };

  // 如果需要认证，添加认证头
  if (requiresAuth) {
    const authHeader = getAuthHeader();
    console.log('🔑 使用认证头:', authHeader);
    Object.assign(headers, authHeader);
  }
  
  try {
    const response = await fetch(url, {
      ...options,
      headers,
      mode: 'cors',
      credentials: 'same-origin',
    });
    
    console.log(`📡 API响应状态: ${response.status} ${response.statusText}`);
    
    // 处理 401 未授权错误（令牌过期）
    if (response.status === 401 && requiresAuth) {
      console.log('🔄 令牌已过期，尝试刷新...');
      const newToken = await refreshAuthToken();
      
      if (newToken) {
        // 使用新令牌重试请求
        console.log('🔑 使用新令牌重试请求');
        headers.Authorization = `Bearer ${newToken}`;
        
        const retryResponse = await fetch(url, {
          ...options,
          headers,
          mode: 'cors',
          credentials: 'same-origin',
        });
        
        if (retryResponse.ok) {
          console.log('🎉 使用新令牌重试成功');
          return await retryResponse.json();
        } else {
          console.error('❌ 使用新令牌重试失败:', retryResponse.status);
        }
      } else {
        // 刷新令牌失败，需要重新登录
        console.error('❌ 刷新令牌失败，需要重新登录');
        // 清除令牌信息并重定向到登录页
        localStorage.removeItem('token');
        localStorage.removeItem('refreshToken');
        localStorage.removeItem('isLoggedIn');
        window.location.href = '/login';
      }
    }
    
    let data;
    try {
      data = await response.json();
      console.log('📄 API响应数据:', data);
    } catch (e) {
      console.error('❌ API响应解析失败:', e);
      data = { 
        success: false,
        message: '服务器响应解析失败',
        data: null
      };
    }
    
    // 特殊处理积分不足情况 (400状态码)
    if (response.status === 400 && data.detail && data.detail.includes('积分不足')) {
      return {
        success: false,
        message: data.detail || '积分不足,请先购买积分',
        isInsufficientPoints: true,
        data: null
      };
    }
    
    if (!response.ok) {
      console.error(`❌ API请求失败: ${response.status} ${data.message || data.detail || ''}`);
      throw new Error(data.message || data.detail || `请求失败: ${response.status}`);
    }
    
    // 直接返回API的原始响应，不做包装
    return data;
  } catch (error) {
    console.error('❌ API 请求错误:', error);
    
    // 处理特定类型的错误
    if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
      return { 
        success: false, 
        message: '网络请求失败，可能是CORS或网络连接问题',
        data: null
      };
    }
    
    return { 
      success: false, 
      message: error.message || '请求失败，请稍后重试',
      data: null
    };
  }
};

// 用户认证相关 API
const auth = {
  // 刷新Token
  refreshToken: async () => {
    return await refreshAuthToken();
  },
  
  // 用户注册
  register: async (userData) => {
    try {
      const response = await fetchAPI(API_ROUTES.register, {
        method: 'POST',
        body: JSON.stringify(userData),
      });
      
      // Even if the API returns success:false with a 200 status code, 
      // we still want to preserve the message
      if (!response.success && response.message) {
        return {
          success: false,
          error: response.message || '注册失败',
          data: response.data
        };
      }
      
      return response;
    } catch (error) {
      console.error('注册请求错误:', error);
      return { 
        success: false, 
        error: error.message || '注册失败，请稍后重试',
        isNetworkError: error.name === 'TypeError' && error.message.includes('Failed to fetch')
      };
    }
  },
  
  // 用户登录 (预留)
  login: async (credentials) => {
    try {
      const response = await fetchAPI(API_ROUTES.login, {
        method: 'POST',
        body: JSON.stringify(credentials),
      });
      
      // Ensure we have a consistent response structure
      if (response.success) {
        // If the API returns data in a nested format, normalize it
        if (response.data && response.data.data) {
          // Return as is if data.data structure exists
          return response;
        } else {
          // Normalize the data structure if the API returns a flattened format
          return {
            success: true,
            data: response.data || {
              token: response.token,
              refresh_token: response.refresh_token,
              userData: response.userData || { username: credentials.username },
              points: response.points || 0
            }
          };
        }
      }
      
      return response;
    } catch (error) {
      console.error('登录请求错误:', error);
      return { 
        success: false, 
        error: error.message || '登录失败，请稍后重试',
        isNetworkError: error.name === 'TypeError' && error.message.includes('Failed to fetch')
      };
    }
  },
  
  // 获取用户积分
  getUserScore: async () => {
    // 调用API获取积分信息
    const response = await fetchAPI(API_ROUTES.getUserScore, {
      method: 'GET',
    }, true); // 需要认证
    
    // 确保API返回的是成功响应，返回原始响应结构
    return response;
  },
  
  // 充值积分
  rechargePoints: async (rechargeData) => {
    return await fetchAPI(API_ROUTES.rechargePoints, {
      method: 'POST',
      body: JSON.stringify(rechargeData),
    }, true); // 需要认证
  },
  
  // 检查用户签到状态
  checkSignInStatus: async () => {
    try {
      console.log('调用签到状态检查接口:', API_ROUTES.checkSignIn);
      const response = await fetchAPI(API_ROUTES.checkSignIn, {
        method: 'GET',
      }, true); // 需要认证
      
      console.log('签到状态原始响应:', response);
      
      // 确保提取正确的is_signed值
      const isSigned = response.data && typeof response.data.is_signed !== 'undefined' 
        ? response.data.is_signed 
        : false;
      
      console.log('提取的签到状态:', isSigned);
      
      return {
        success: response.success,
        message: response.message || '查询签到状态成功',
        isSigned: isSigned
      };
    } catch (error) {
      console.error('查询签到状态错误:', error);
      return {
        success: false,
        message: error.message || '查询签到状态失败，请稍后重试',
        isSigned: false,
        isNetworkError: error.name === 'TypeError' && error.message.includes('Failed to fetch')
      };
    }
  },
  
  // 用户每日签到
  signIn: async () => {
    try {
      const response = await fetchAPI(API_ROUTES.signIn, {
        method: 'POST',
        body: JSON.stringify({}),
      }, true); // 需要认证
      
      return {
        success: response.success,
        message: response.message || (response.success ? '签到成功' : '签到失败'),
        data: response.data,
        alreadySigned: !response.success && response.message?.includes('今日已签到')
      };
    } catch (error) {
      console.error('签到请求错误:', error);
      return {
        success: false,
        message: error.message || '签到失败，请稍后重试',
        isNetworkError: error.name === 'TypeError' && error.message.includes('Failed to fetch')
      };
    }
  },
  
  // 更新用户生日
  updateBirthday: async (birthday) => {
    try {
      const response = await fetchAPI(API_ROUTES.updateBirthday, {
        method: 'PUT',
        body: JSON.stringify({ birthday }),
      }, true); // 需要认证
      
      return {
        success: response.success,
        message: response.message || (response.success ? '生日更新成功' : '生日更新失败'),
        data: response.data
      };
    } catch (error) {
      console.error('更新生日请求错误:', error);
      return {
        success: false,
        message: error.message || '更新生日失败，请稍后重试',
        isNetworkError: error.name === 'TypeError' && error.message.includes('Failed to fetch')
      };
    }
  },
  
  // 更新用户性别
  updateGender: async (gender) => {
    try {
      const response = await fetchAPI(API_ROUTES.updateGender, {
        method: 'PUT',
        body: JSON.stringify({ gender }),
      }, true); // 需要认证
      
      return {
        success: response.success,
        message: response.message || (response.success ? '性别更新成功' : '性别更新失败'),
        data: response.data
      };
    } catch (error) {
      console.error('更新性别请求错误:', error);
      return {
        success: false,
        message: error.message || '更新性别失败，请稍后重试',
        isNetworkError: error.name === 'TypeError' && error.message.includes('Failed to fetch')
      };
    }
  },
  
  // 获取用户详情
  getUserDetail: async () => {
    try {
      const response = await fetchAPI(API_ROUTES.getUserDetail, {
        method: 'GET',
      }, true); // 需要认证
      
      return {
        success: response.success,
        message: response.message || (response.success ? '获取用户详情成功' : '获取用户详情失败'),
        data: response.data
      };
    } catch (error) {
      console.error('获取用户详情请求错误:', error);
      return {
        success: false,
        message: error.message || '获取用户详情失败，请稍后重试',
        isNetworkError: error.name === 'TypeError' && error.message.includes('Failed to fetch')
      };
    }
  },
};

// 命理咨询 API
const ask = {
  // 发送问题 (常规请求，返回完整回答)
  askQuestion: async (question) => {
    try {
      // 直接返回API的原始响应结构，不做额外处理
      return await fetchAPI(API_ROUTES.ask, {
        method: 'POST',
        body: JSON.stringify({ question }),
      }, true); // 需要认证
    } catch (error) {
      console.error('命理咨询API错误:', error);
      return { 
        success: false, 
        message: error.message || '请求失败，请稍后重试',
        data: null
      };
    }
  },
  
  // 流式发送问题 (返回 ReadableStream)
  askQuestionStream: async (question, onChunk, onComplete, onError) => {
    try {
      const token = localStorage.getItem('token');
      const headers = {
        'Content-Type': 'application/json',
      };
      
      // 如果有认证令牌，添加到请求头
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
      
      // 发送 fetch 请求获取服务器发送事件流
      const response = await fetch(`${API_BASE_URL}${API_ROUTES.ask}`, {
        method: 'POST',
        headers,
        body: JSON.stringify({ question }),
      });
      
      // 特殊处理积分不足情况 (400状态码)
      if (!response.ok) {
        let errorData = {};
        try {
          errorData = await response.json();
        } catch (e) {
          console.error('解析错误响应失败:', e);
        }
        
        // 创建自定义错误对象
        const error = new Error(errorData.detail || `HTTP error! Status: ${response.status}`);
        error.response = {
          status: response.status,
          data: errorData
        };
        
        // 特殊处理积分不足情况
        if (response.status === 400 && errorData.detail && errorData.detail.includes('积分不足')) {
          error.isInsufficientPoints = true;
        }
        
        throw error;
      }
      
      // 获取响应体的读取流
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';
      
      // 处理数据流的函数
      const processStream = async () => {
        try {
          while (true) {
            const { done, value } = await reader.read();
            
            if (done) {
              // 处理最后一块数据
              if (buffer) {
                processBuffer(buffer);
              }
              if (onComplete) onComplete();
              break;
            }
            
            // 将二进制数据解码为文本
            const chunk = decoder.decode(value, { stream: true });
            buffer += chunk;
            
            // 处理缓冲区中的数据行
            processBuffer(buffer);
            
            // 保留尚未处理完的部分
            const lastNewlineIndex = buffer.lastIndexOf('\n\n');
            if (lastNewlineIndex !== -1) {
              buffer = buffer.substring(lastNewlineIndex + 2);
            }
          }
        } catch (err) {
          console.error('流处理错误:', err);
          if (onError) onError(err);
        }
      };
      
      // 处理数据缓冲区
      const processBuffer = (buffer) => {
        const lines = buffer.split('\n\n');
        
        for (let i = 0; i < lines.length - 1; i++) {
          const line = lines[i].trim();
          if (line.startsWith('data: ')) {
            const data = line.substring(6); // 移除 "data: " 前缀
            
            if (data === '[DONE]') {
              // 流结束标志
              if (onComplete) onComplete();
            } else {
              // 处理数据块
              if (onChunk) onChunk(data);
            }
          }
        }
      };
      
      // 开始处理流
      processStream();
      
      return { success: true };
    } catch (error) {
      console.error('流式命理咨询API错误:', error);
      if (onError) onError(error);
      return { 
        success: false, 
        message: error.message || '请求失败，请稍后重试'
      };
    }
  }
};

// 订单相关 API
const order = {
  // 创建订单
  createOrder: async (orderData) => {
    return await fetchAPI(API_ROUTES.createOrder, {
      method: 'POST',
      body: JSON.stringify(orderData),
    }, true); // 需要认证
  },
  
  // 创建支付链接
  createPayUrl: async (orderTradeNo) => {
    return await fetchAPI(API_ROUTES.createPayUrl, {
      method: 'POST',
      body: JSON.stringify({ order_trade_no: orderTradeNo }),
    }, true); // 需要认证
  },
};

// 导出所有 API 服务
export default {
  auth,
  ask,
  order,
  // 其他 API 模块可以根据需要添加
};

// 导出 getAuthHeader 函数
export { getAuthHeader };